package com.ruoyi.system.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.entity.Back;
import com.ruoyi.system.mapper.BackMapper;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.*;
/**
 * 岗位信息操作处理
 * 
 * @author ruoyi
 */
@RestController
@RequiredArgsConstructor
@CrossOrigin
@RequestMapping("/system/back")
public class BackController extends BaseController
{
    @Autowired
    private BackMapper backMapper;

    /**
     * 获取岗位列表
     */
    @GetMapping("/list")
    public AjaxResult list(PageInfo<Back> page, Back back)
    {
        String string = "";
         if (back.getCategory() != null && back.getCategory().size() > 0){
             string = "%" + back.getCategory().get(1) + "%";
         }

        PageHelper.startPage(page.getPageNum(),page.getPageSize());
         List<Back> backs = backMapper.selectList(Wrappers.<Back>lambdaQuery()
                .eq(back.getName() != null && !Objects.equals(back.getName(), ""), Back::getName, back.getName())
                .eq(back.getYear() != null && !Objects.equals(back.getYear(), ""), Back::getYear, back.getYear())
                 .apply(back.getCategory() != null && back.getCategory().size()>0, "category like {0}", string)
        );

        return AjaxResult.success(new PageInfo<>(backs));
    }

    /**
     * 根据岗位编号获取详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable Long id)
    {
         Back back = backMapper.selectById(id);
        return AjaxResult.success(back);
    }

    /**
     * 新增岗位
     */
    @PostMapping("add")
    public AjaxResult add( @RequestBody Back back)
    {
         Back backDTO = backMapper.selectOne(Wrappers.<Back>lambdaQuery()
                .eq(Back::getName, back.getName()));
        if (backDTO!=null)
        {
            return error("新增岗位'" + back.getName() + "'失败，岗位名称已存在");
        }
        backMapper.insert(back);
        return AjaxResult.success();
    }

    /**
     * 修改岗位
     */
    @PutMapping("update")
    public AjaxResult edit(@RequestBody Back back)
    {
        Back backDTO = backMapper.selectOne(Wrappers.<Back>lambdaQuery()
                .eq(Back::getName, back.getName())
                .ne(Back::getId, back.getId())
        );
        if (backDTO!=null)
        {
            return error("修改岗位'" + back.getName() + "'失败，岗位名称已存在");
        }
        backMapper.updateById(back);
        return AjaxResult.success();
    }

    /**
     * 删除岗位
     */
    @Log(title = "岗位管理", businessType = BusinessType.DELETE)
    @PostMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(backMapper.deleteBatchIds(Arrays.asList(ids)));
    }

    private final MinioClient minioClient;
    @Value("${minio.bucket}")
    public String bucket;
    @Value("${minio.url}")
    private String baseurl;
    @PostMapping("upload")
    public String upload(@RequestPart MultipartFile file) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        if(!file.isEmpty()){
//            System.err.println(minioClient.bucketExists(BucketExistsArgs.builder().bucket("xingnetstudy").build()));
            //上传
            minioClient.putObject(PutObjectArgs.builder().
                    bucket(bucket). //桶的名称
                            object(file.getOriginalFilename()). //对象名
                            stream(file.getInputStream(),file.getSize(),-1). //文件内容 参数说明:1.文件内容 流 2.文件大小 3.分片
                            contentType(file.getContentType()).//设置文件的类型
                            build());
//            //返回  文件的访问地址
            return "http://127.0.0.1:9000/exam-xxs/"+file.getOriginalFilename();
        }
        return "fail";
    }

    //测试git
}
